package com.zhenyi.zhaozheng.web;

import org.hashids.Hashids;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.zhaozheng.common.model.ZzActivity;
import com.zhenyi.core.ZIndexController;

public class HomeController extends ZIndexController {

	protected Hashids hashids = new Hashids("zhaozheng", 8);

	@Override
	public void index() {
		String code = getPara(0);
		if (StrKit.isBlank(code)) {
			renderFailure("activity code is required");
			return;
		}
		Long activityId = null;
		try {
			activityId = hashids.decode(code)[0];
		} catch (Exception e) {
			LogKit.warn("zz activity code decode erorr: " + code);
			e.printStackTrace();
		}
		ZzActivity activity = ZzActivity.dao.findById(activityId);
		if (activity == null) {
			renderError(404);
			return;
		}
		// setInfoItem(JsonKit.toJson(activity));
		setData("info", activity);
		setAttr("title", activity.getTitle());
		render("/zz/activityInfo.html");
	}

	public void enroll() {
		String code = getPara(0);
		if (StrKit.isBlank(code)) {
			renderFailure("activity code is required");
			return;
		}
		Long activityId = null;
		try {
			activityId = hashids.decode(code)[0];
		} catch (Exception e) {
			LogKit.warn("zz activity code decode erorr: " + code);
			e.printStackTrace();
		}
		ZzActivity activity = ZzActivity.dao.findById(activityId);
		if (activity == null) {
			renderError(404);
			return;
		}
		if (!activity.getStatus().equals(1)) {
			renderFailure(500, "非报名时间");
			return;
		}
		setAttr("code", code);
		setAttr("activityTitle", activity.getTitle());
		render("/zz/enroll.html");
	}

	public void attend() {
		String code = getPara(0);
		if (StrKit.isBlank(code)) {
			renderFailure("activity code is required");
			return;
		}
		Long activityId = null;
		try {
			activityId = hashids.decode(code)[0];
		} catch (Exception e) {
			LogKit.warn("zz activity code decode erorr: " + code);
			e.printStackTrace();
		}
		ZzActivity activity = ZzActivity.dao.findById(activityId);
		if (activity == null) {
			renderError(404);
			return;
		}
		if (!activity.getStatus().equals(2)) {
			renderFailure(500, "活动尚未开始/活动已结束");
			return;
		}
		setAttr("code", code);
		setAttr("activityTitle", activity.getTitle());
		render("/zz/attend.html");
	}

	public void success() {
		String code = getPara(0);
		if (StrKit.isBlank(code)) {
			renderFailure("activity code is required");
			return;
		}
		Long activityId = null;
		try {
			activityId = hashids.decode(code)[0];
		} catch (Exception e) {
			LogKit.warn("zz activity code decode erorr: " + code);
			e.printStackTrace();
		}
		ZzActivity activity = ZzActivity.dao.findById(activityId);
		if (activity == null) {
			renderError(404);
			return;
		}
		setAttr("code", code);
		setAttr("activityTitle", activity.getTitle());
		render("/zz/success.html");

	}
}
